/**
* Copyright 2009, Jethro Grassie, Creative Jar Technology Ltd (http://www.cjtech.co.uk)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
**/

package com.adobe.cairngorm.control;

import com.adobe.cairngorm.CairngormError;
import com.adobe.cairngorm.CairngormMessageCodes;
import com.adobe.cairngorm.commands.Command;

import java.util.HashMap;
import java.lang.Class;

import javafx.reflect.*;

public class FrontController
{
    protected var commands:HashMap = new HashMap();

    public function addCommand(commandName:String, commandRef:Class):Void
    {
        if(commands.containsKey(commandName))
        {
            throw CairngormError
            { 
                errorCode: CairngormMessageCodes.COMMAND_ALREADY_REGISTERED
                data: commandName
            };
        }

        commands.put(commandName, commandRef);
        CairngormEventDispatcher.getInstance().addEventListener(commandName, executeCommand);
    }

    public function removeCommand(commandName:String):Void
    {
        if(not commands.containsKey(commandName))
        {
            throw CairngormError
            {
                errorCode: CairngormMessageCodes.COMMAND_NOT_REGISTERED
                data: commandName
            };
        }

        CairngormEventDispatcher.getInstance().removeEventListener(commandName, executeCommand);
        commands.remove(commandName);
    }

    protected function executeCommand(event:CairngormEvent):Void
    {
        var context:FXLocal.Context = FXLocal.getContext();
        var commandToInitialise:FXLocal.ClassType = context.makeClassRef(getCommand(event.type));
        var commandToExecute:Command = (commandToInitialise.allocate() as FXLocal.ObjectValue).asObject() as Command;
        commandToExecute.execute(event);
    }

    protected function getCommand(commandName:String):Class
    {
        if (not commands.containsKey(commandName))
        {
            throw CairngormError
            {
                errorCode: CairngormMessageCodes.COMMAND_NOT_FOUND
                data: commandName
            };
        }

        var command:Class = commands.get(commandName) as Class;
        return command;
    }      
}   

